package com.iot08.admin.service;

import com.iot08.admin.service.page.PageVO;
import com.iot08.admin.service.page.PageableImpl;
import com.iot08.common.entity.admin.SysUser;
import com.iot08.common.entity.app.Adversters;
import com.iot08.common.entity.app.AdverstersComInfo;
import com.iot08.common.response.Response;
import com.iot08.common.service.base.BaseService;
import com.iot08.common.utils.RandomUtil;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @version 1.0
 * @Description: 广告业务逻辑
 * @time: 2020/10/22 11:40
 * @author: Rock
 */
@Service
public class AdverstersService extends BaseService<Adversters> {

    @Resource
    private OperationService operationService;
    @Resource
    private AdverstersComInfoService adverstersComInfoService;

    /**
     * @param shortName
     * @time: 2020/10/27 9:13
     * @author: Rock
     * @version 1.0
     */
    public Adversters getByShortName(String shortName) {
        return this.findOne(new Query(Criteria.where("short_name").is(shortName)));
    }

    /**
     * @param page
     * @time: 2020/10/27 8:49
     * @author: Rock
     * @version 1.0
     */
    public Page<Adversters> list(PageVO page) {
        PageableImpl pageable = new PageableImpl();
        page.setSort(Sort.by(Sort.Order.desc("createtime")));
        pageable.setPage(page);
        Query query = new Query();
        long count = this.count(query);
        page.setTotalResult((int) count);
        List<Adversters> list = this.find(query.with(pageable));
        Page<Adversters> result = new PageImpl<Adversters>(list, pageable, count);
        return result;
    }

    /**
     * 添加广告商
     *
     * @param adversters
     * @param user
     * @param ip
     * @time: 2020/10/27 8:49
     * @author: Rock
     * @version 1.0
     */
    public void add(Adversters adversters, SysUser user, String ip) {
        if (adversters != null && getByShortName(adversters.getShortName()) == null) {
            adversters.setAdversterid(RandomUtil.getRandomStr(6));
            adversters.setCreatetime(new Date());
            this.save(adversters);
            operationService.add(user, ip, "广告配置", "添加",
                    String.format("添加运营版广告配置: %s ", adversters.getName()));
        }
    }

    /**
     * @param adversters
     * @param user
     * @param ip
     * @time: 2020/10/27 8:48
     * @author: Rock
     * @version 1.0
     */
    public void update(Adversters adversters, SysUser user, String ip) {
        Update update = new Update();
        update.set("name", adversters.getName());
        update.set("short_name", adversters.getShortName());
        update.set("index", adversters.getIndex());
        update.set("modifytime", new Date());
        this.updateById(new ObjectId(adversters.getId()), update);
        operationService.add(user, ip, "广告配置", "编辑",
                String.format("修改运营版广告配置: %s ", adversters.getName()));
    }

    /**
     * @param id
     * @param user
     * @param ip
     * @time: 2020/10/23 9:32
     * @author: Rock
     * @version 1.0
     */
    public Response<Object> del(String id, SysUser user, String ip) {
        if (ObjectId.isValid(id)) {
            ObjectId oid = new ObjectId(id);
            Adversters adversters = this.findById(oid);
            if (adversters != null) {
                this.delById(oid);
                operationService.add(user, ip, "广告配置", "删除",
                        String.format("删除运营版广告配置: %s ", adversters.getName()));
                return Response.successResponse();
            }
        }
        return Response.failedResponse();
    }

    /**
     * @time: 2020/10/27 15:11
     * @author: Rock
     * @version 1.0
     */
    public Map<String, Object> getConfig() {
        List<Document> result = new ArrayList<>();
        AdverstersComInfo ac = adverstersComInfoService.getById("main_info");
        List<Adversters> list = this.find(new Query().with(Sort.by(Sort.Order.desc("index"))));
        if (ac != null && list != null && !list.isEmpty()) {
            for (Adversters ad : list) {
                String key = ad.getShortName();
                Document doc = new Document();
                doc.append("name", new Document().append("name", key + "_name").append("value", ad.getName()));
                doc.append("short_name", new Document().append("name", key + "_short_name").append("value", ad.getShortName()));
                doc.append("status", new Document().append("name", key + "_status").append("value", ad.getStatus()));
                doc.append("start_time1", new Document().append("name", key + "_start_time1").append("value", ad.getStartTime1()));
                doc.append("end_time1", new Document().append("name", key + "_end_time1").append("value", ad.getEndTime1()));
                doc.append("start_time2", new Document().append("name", key + "_start_time2").append("value", ad.getStartTime2()));
                doc.append("end_time2", new Document().append("name", key + "_end_time2").append("value", ad.getEndTime2()));
                doc.append("start_time3", new Document().append("name", key + "_start_time3").append("value", ad.getStartTime3()));
                doc.append("end_time3", new Document().append("name", key + "_end_time3").append("value", ad.getEndTime3()));
                doc.append("ADweight", new Document().append("name", key + "_ADweight").append("value", ad.getADweight()));
                doc.append("index", ad.getIndex());
                result.add(doc);
            }
            Map<String, Object> map = new HashMap<>();
            map.put("adverstersComInfo", ac);
            map.put("adversters", list);
            map.put("data", result);
            return map;
        }
        return null;
    }

    /**
     * @param acf
     * @param request
     * @time: 2020/10/27 15:55
     * @author: Rock
     * @version 1.0
     */
    public void config(AdverstersComInfo acf, HttpServletRequest request, SysUser u) {
        String firstADName = "";
        String secondADName = "";
        List<Adversters> list = this.find(new Query().with(Sort.by(Sort.Order.asc("index"))));
        if (list != null && !list.isEmpty()) {
            int index = 0;
            for (Adversters ad : list) {
                if (index == 0) {
                    if ("1".equals(ad.getIndex())) {
                        firstADName = ad.getShortName();
                    }
                } else if (index == 1) {
                    if ("2".equals(ad.getIndex())) {
                        secondADName = ad.getShortName();
                    }
                }
                String key = ad.getShortName();
                Update update = new Update();
                update.set("status", request.getParameter(key + "_status"));
                update.set("start_time1", request.getParameter(key + "_start_time1"));
                update.set("end_time1", request.getParameter(key + "_end_time1"));
                update.set("start_time2", request.getParameter(key + "_start_time2"));
                update.set("end_time2", request.getParameter(key + "_end_time2"));
                update.set("start_time3", request.getParameter(key + "_start_time3"));
                update.set("end_time3", request.getParameter(key + "_end_time3"));
                update.set("ADweight", request.getParameter(key + "_ADweight"));
                update.set("modifytime", new Date());
                Query query = new Query(Criteria.where("short_name").is(key));
                this.update(query, update);
                index++;
            }
        }

        Map<String, Map<String, Object>> adFillDic = new HashMap<>();
        Map<String, Object> first = new HashMap<>();
        first.put("adverster_name", firstADName);
        Map<String, Object> second = new HashMap<>();
        second.put("adverster_name", secondADName);
        adFillDic.put("first", first);
        adFillDic.put("second", second);

        AdverstersComInfo ac = adverstersComInfoService.getById("main_info");
        if (ac == null){
            ac = new AdverstersComInfo();
            ac.setId("main_info");
        }
        ac.setAdFillDic(adFillDic);
        ac.setAdStartFun(acf.getAdStartFun());
        ac.setAdFailUserADName(acf.getAdFailUserADName());
        ac.setAppAuditAccount(acf.getAppAuditAccount());
        ac.setAppInternalADswitch(acf.getAppInternalADswitch());
        ac.setApiWordLink(acf.getApiWordLink());
        ac.setAppOpenAdvertSwitch(acf.getAppOpenAdvertSwitch());
        ac.setInternalADFreeVersion(acf.getInternalADFreeVersion());
        ac.setUpdateTime(new Date());
//        Update acfUpdate = new Update();
//        acfUpdate.set("adFillDic", adFillDic);
//        acfUpdate.set("adStartFun", acf.getAdStartFun());
//        acfUpdate.set("adFailUserADName", acf.getAdFailUserADName());
//        acfUpdate.set("appAuditAccount", acf.getAppAuditAccount());
//        acfUpdate.set("appInternalADswitch", acf.getAppInternalADswitch());
//        acfUpdate.set("api_word_link", acf.getApiWordLink());
//        acfUpdate.set("app_open_advert_switch", acf.getAppOpenAdvertSwitch());
//        acfUpdate.set("internalADFreeVersion", acf.getInternalADFreeVersion());
//        acfUpdate.set("updateTime", new Date());
//        adverstersComInfoService.updateById("main_info", acfUpdate);
        adverstersComInfoService.save(ac);
        operationService.add(u, request.getRemoteAddr(), "广告配置", "配置", "修改广告配置");
    }
}
